package com.yxw.live_vod_boot.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxw.live_vod_boot.dto.LiveLikeDTO;
import com.yxw.live_vod_boot.entity.YxLiveLikeEntity;
import com.yxw.live_vod_boot.exception.GlobalCustomerException;
import com.yxw.live_vod_boot.mapper.LiveLikeMapper;
import com.yxw.live_vod_boot.service.LiveLikeService;
import com.yxw.live_vod_boot.utils.RedisManager;
import com.yxw.live_vod_boot.vo.LiveLikeInfoVo;
import com.yxw.live_vod_boot.vo.VideoLikeInfoVo;
import com.yxw.yxnet_cd_center.common.constant.RedisIdConstant;
import com.yxw.yxnet_cd_center.common.enums.ErrorCodeEnum;
import com.yxw.yxnet_cd_center.common.utils.BaseResult;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class LiveLikeServiceImpl extends ServiceImpl<LiveLikeMapper, YxLiveLikeEntity> implements LiveLikeService {

    @Autowired
    private RedisManager redisManager;

    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private LiveLikeMapper liveLikeMapper;

    /**
     * 直播点赞
     */
    @Override
    public void doLiveLike(LiveLikeDTO dto) {
        //查询总点赞数量
        long cnt = 0L;
        Object obj = redisManager.get(RedisIdConstant.LIVE_VIDEO_LIKE_CNT + ":" + dto.getLiveId());
        if (null != obj) {
            cnt = ((Integer) obj).longValue();
        }
        //增加点赞
        redisManager.addBySet(RedisIdConstant.LIVE_VIDEO_LIKE + ":" + dto.getLiveId(), dto.getUserId());
        //点赞数量加1
        redisManager.set(RedisIdConstant.LIVE_VIDEO_LIKE_CNT + ":" + dto.getLiveId(), cnt + 1);
        // 添加新增点赞记录
        String value = dto.getLiveId() + ":" + dto.getUserId() + ":" + System.currentTimeMillis();
        redisManager.addBySet(RedisIdConstant.LIVE_VIDEO_LIKE_ADD + ":" + dto.getLiveId(), value);
    }

    /**
     * 查询当前直播总点赞量
     */
    @Override
    public BaseResult getLiveLikeInfo(String liveId) {
        LiveLikeInfoVo vo = new LiveLikeInfoVo();
        //查询点赞量
        long cnt = 0L;
        Object obj = redisManager.get(RedisIdConstant.LIVE_VIDEO_LIKE_CNT + ":" + liveId);
        if (null != obj) {
            cnt = ((Integer) obj).longValue();
        }
        vo.setLikeCnt(cnt);
        return BaseResult.doSuccess(vo, "查询成功");
    }

    /**
     * 点赞直播信息从Redis添加到数据库
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addLikeRecord() {
        // 查询新增点赞前缀的Redis键
        Set<String> addKeys = redisTemplate.keys(RedisIdConstant.LIVE_VIDEO_LIKE_ADD + ":" + "*");
        List<YxLiveLikeEntity> likeList = new ArrayList<>();
        if (addKeys != null) {
            for (String key : addKeys) {
                // 获取ID
                String liveId = key.split(":")[1];
                // 查询视频对应的点赞人
                Set<Object> values = redisTemplate.opsForSet().members(key);
                // 将点赞信息保存到List中
                if (values != null) {
                    for (Object value : values) {
                        String[] params = ((String) value).split(":");
                        String userId = params[1];
                        String createTimeStr = params[2];
                        try {
                            long createTimeMillis = Long.parseLong(createTimeStr);
                            Instant createTime = Instant.ofEpochMilli(createTimeMillis);
                            YxLiveLikeEntity like = new YxLiveLikeEntity();
                            like.setLiveId(liveId);
                            like.setUserId(userId);
                            like.setLikeTime(Date.from(createTime));
                            like.setCreateTime(new Date());
                            likeList.add(like);
                        } catch (NumberFormatException e) {
                            // 处理时间戳解析异常
                            throw new GlobalCustomerException(ErrorCodeEnum.TIME_TRANCE_ERROR);
                        }
                    }
                }
                // 删除Redis中保存的点赞信息
                redisTemplate.delete(key);
            }
        }
        // 批量写入数据库
        if (!likeList.isEmpty()) {
            int size = likeList.size();
            int pageSize = 1500;
            int num = size % pageSize == 0 ? size / pageSize : size / pageSize + 1;
            for (int i = 0; i < num; i++) {
                liveLikeMapper.saveByBatch(likeList.stream().skip((long) i * pageSize).limit(pageSize).collect(Collectors.toList()));
            }
        }
    }
}